<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getRatesIndexApi, deleteRateApi } from "@/api/calculator"
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight, Operation } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import RateForm from "./components/RateForm.vue"
import RateQuery from "./components/RateQuery.vue"

defineOptions({
  // 命名当前组件
  name: "CalculatorIndex"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增改
const formRef = ref<InstanceType<typeof RateForm> | null>(null)
const queryRef = ref<InstanceType<typeof RateQuery> | null>(null)

const handleAdd = () => {
  formRef.value?.openAdd()
}

const handleFormSuccess = () => {
  getTableData()
}

const handleQuery = () => {
  queryRef.value?.openQuery()
}

const handleQueryResult = (result: any) => {
  console.log("查询结果：", result)
}
//#endregion

//#region 删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`正在删除利率，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteRateApi({ id: row.rate_id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row: any) => {
  formRef.value?.openEdit(row)
}
//#endregion

//#region 查
const tableData = ref<any[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: ""
})
const getTableData = () => {
  loading.value = true
  getRatesIndexApi({
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize
  })
    .then((res: any) => {
      paginationData.total = res.data.total
      tableData.value = res.data.data
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增利率</el-button>
          <el-button type="success" :icon="Operation" @click="handleQuery">查询利率</el-button>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="amount_range" label="金额区间" align="center" />
          <el-table-column prop="month" label="生效月份" align="center" />
          <el-table-column prop="rate" label="利率值" align="center">
            <template #default="scope">
              <span v-if="scope.row.rate_mode === 'FIXED'">{{ scope.row.rate }}%</span>
              <span v-else-if="scope.row.rate_mode === 'FLOAT'">{{ scope.row.rate }}%</span>
              <span v-else-if="scope.row.rate_mode === 'FIXED_AMOUNT'">¥{{ scope.row.rate }}</span>
              <span v-else>{{ scope.row.rate }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="rate_mode" label="利率模式" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.rate_mode === 'FIXED'" type="success">固定比例</el-tag>
              <el-tag v-else-if="scope.row.rate_mode === 'FLOAT'" type="warning">浮动</el-tag>
              <el-tag v-else-if="scope.row.rate_mode === 'FIXED_AMOUNT'" type="info">固定金额</el-tag>
              <el-tag v-else>{{ scope.row.rate_mode }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" align="center" />
          <el-table-column prop="updated_at" label="更新时间" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改表单组件 -->
    <RateForm ref="formRef" @success="handleFormSuccess" />
    <!-- 利率查询组件 -->
    <RateQuery ref="queryRef" @query-result="handleQueryResult" />
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
